package com.rc.saas.tenant.controller.tenant;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.elec.ElecStation;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.StatisticsSearch;
import com.rc.saas.tenant.search.elec.ElecSationSearch;
import com.rc.saas.tenant.service.elec.ElecPileService;
import com.rc.saas.tenant.service.elec.ElecStationService;
import com.rc.saas.tenant.service.order.OrderInfoService;
import com.rc.saas.tenant.service.tenant.ConsoleService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.elec.ChargeLeaderboard;
import com.rc.saas.tenant.vo.elec.ElecPileStatusCountVo;
import com.rc.saas.tenant.vo.elec.StationAllDataVo;
import com.rc.saas.tenant.vo.elec.StatisticsStationNum;
import com.rc.saas.tenant.vo.order.OrderAllDataVo;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by sven on 2019/12/22
 */
@Controller
@RequestMapping("/console")
public class ConsoleController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(ConsoleController.class);

    @Autowired
    private ElecStationService elecStationService;

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private ConsoleService consoleService;

    @Autowired
    private RedisLoader redisLoader;

    /**
     * 站点总览数据
     */
    @RequestMapping("/selectStationAllData")
    @ResponseBody
    public TResponse selectStationAllData() {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantOperatorCode() != null) {
            StationAllDataVo stationAllDataVo = elecStationService.selectStationAllDataOperator(user.getTenantOperatorCode());
            return TResponse.SUCCESS_DATA(stationAllDataVo);
        }
        StationAllDataVo stationAllDataVo = elecStationService.selectStationAllData(user.getTenantCode());
        return TResponse.SUCCESS_DATA(stationAllDataVo);
    }

    /**
     * 订单总览数据
     */
    @RequestMapping("/selectTenantOrderByDay")
    @ResponseBody
    public TResponse selectTenantOrderByDay(String dateType, String todayData) {
        OrderAllDataVo orderAllDataVo = null;
        if (todayData != null && !"".equals(todayData)) {
            orderAllDataVo = JSON.parseObject(todayData, OrderAllDataVo.class);
        }
        //dateType: 今天:1  本月:2  本年:3
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantOperatorCode() != null) {
            OrderAllDataVo newOrderAllDataVo = orderInfoService.selectTenantOrderByDayOperator(user.getTenantOperatorCode(), dateType, orderAllDataVo);
            newOrderAllDataVo.setChargingTimeCount(newOrderAllDataVo.getChargingTimeCount().divide(new BigDecimal(60 * 60), 1, BigDecimal.ROUND_HALF_UP));
            return TResponse.SUCCESS_DATA(newOrderAllDataVo);
        }
        OrderAllDataVo newOrderAllDataVo = orderInfoService.selectTenantOrderByDay(user.getTenantCode(), dateType, orderAllDataVo);
        //将毫秒转换为小时
        newOrderAllDataVo.setChargingTimeCount(newOrderAllDataVo.getChargingTimeCount().divide(new BigDecimal(60 * 60), 1, BigDecimal.ROUND_HALF_UP));
        return TResponse.SUCCESS_DATA(newOrderAllDataVo);
    }

    /**
     * 桩群充电排榜数据
     */
    @RequestMapping("/selectStationChargeLeaderboard")
    @ResponseBody
    public TResponse selectStationChargeLeaderboard() {

        TenantUser user = ShiroUtils.getSessionUser();

        if (user.getTenantOperatorCode() != null) {
            String stationLeaderboard = (String) redisLoader.get("saas:stationLeaderboard:" + user.getTenantOperatorCode());
            if (stationLeaderboard == null) {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);
                calendar.set(Calendar.MILLISECOND, 0);

                long timeDifference = calendar.getTimeInMillis() - System.currentTimeMillis();

                List<ChargeLeaderboard> chargeLeaderboards = orderInfoService.listStationChargeLeaderboardOperator(user.getTenantOperatorCode());
                if (!CollectionUtils.isEmpty(chargeLeaderboards)) {
                    redisLoader.set("saas:stationLeaderboard:" + user.getTenantOperatorCode(), JSON.toJSONString(chargeLeaderboards), timeDifference);
                }
                return TResponse.SUCCESS_DATA(chargeLeaderboards);
            }
            List<ChargeLeaderboard> chargeLeaderboards = JSONArray.parseArray(stationLeaderboard, ChargeLeaderboard.class);
            return TResponse.SUCCESS_DATA(chargeLeaderboards);
        }

        String stationLeaderboard = (String) redisLoader.get("saas:stationLeaderboard:" + user.getTenantCode());
        if (stationLeaderboard == null) {

            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            long timeDifference = calendar.getTimeInMillis() - System.currentTimeMillis();

            List<ChargeLeaderboard> leaderboard = orderInfoService.listStationChargeLeaderboard(user.getTenantCode());
            if (!CollectionUtils.isEmpty(leaderboard)) {

                Date date = new Date();
                String strDateFormat = "HH";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                Integer hour = new Integer(sdf.format(date));

                if (hour > 6) {
                    redisLoader.set("saas:stationLeaderboard:" + user.getTenantCode(), JSON.toJSONString(leaderboard), timeDifference);
                }
                return TResponse.SUCCESS_DATA(leaderboard);
            }
        }
        List<ChargeLeaderboard> chargeLeaderboards = JSONArray.parseArray(stationLeaderboard, ChargeLeaderboard.class);
        return TResponse.SUCCESS_DATA(chargeLeaderboards);
    }

    /**
     * 返回所有该运营商的桩群和经纬度
     */
    @RequestMapping("/selectStationAndLatiLong")
    @ResponseBody
    public TResponse selectStationAndLatiLong() {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantOperatorCode() != null) {
            List<ElecStation> elecStationList = elecStationService.selectStationAndLatiLongOperator(user.getTenantOperatorCode());
            return TResponse.SUCCESS_DATA(elecStationList);
        }
        BaseSearch baseSearch = new BaseSearch();//兼容性处理
        baseSearch.setTenantCode(user.getTenantCode());
        List<ElecStation> elecStationList = elecStationService.listStationAndLatiLong(user.getTenantCode(), baseSearch);
        return TResponse.SUCCESS_DATA(elecStationList);
    }

    /**
     * 返回电桩状态统计
     */
    @RequestMapping("/selectCountByPileStatus")
    @ResponseBody
    public TResponse selectCountByPileStatus(Long eleStationId) {
        TenantUser user = ShiroUtils.getSessionUser();
        if (user.getTenantOperatorCode() != null) {
            ElecPileStatusCountVo elecPileStatusCountVo = elecPileService.selectCountByPileStatusOperator(user.getTenantOperatorCode(), eleStationId);
            return TResponse.SUCCESS_DATA(elecPileStatusCountVo);
        }
        ElecPileStatusCountVo elecPileStatusCountVo = elecPileService.selectCountByPileStatus(user.getTenantCode(), eleStationId);
        return TResponse.SUCCESS_DATA(elecPileStatusCountVo);
    }

    /**
     * 订单统计
     */
    @ResponseBody
    @RequestMapping("/countAllOrder")
    public TResponse countAllOrder(String dataAuth) {
        StatisticsSearch search = new StatisticsSearch();
        TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        search.setOperatorId(user.getOperatorId());
        search.setEnterpriseId(user.getEnterpriseId());
        search.setDataAuth(dataAuth);
        OrderAllDataVo data = consoleService.countAllOrder(search);
        return TResponse.SUCCESS_DATA(data);
    }

    /**
     * 今日订单统计
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/countTodayOrder")
    public TResponse countTodayOrder(String dataAuth) {
        StatisticsSearch search = new StatisticsSearch();
        TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        search.setOperatorId(user.getOperatorId());
        search.setEnterpriseId(user.getEnterpriseId());
        OrderAllDataVo data = consoleService.countTodayOrder(search);
        return TResponse.SUCCESS_DATA(data);
    }

    /**
     * 站点总览
     */
    @ResponseBody
    @RequestMapping("/countStation")
    public TResponse countStation(String bizType,String dataAuth) {
        TenantUser user = ShiroUtils.getSessionUser();
        ElecSationSearch search = new ElecSationSearch();
        search.setLoginName(user.getLoginName());

        search.setDataAuth(dataAuth);
        String isPlatformAuth = dataAuth.substring(0, 1);
        String isOperatorAuth = dataAuth.substring(1, 2);
        if ("1".equals(isPlatformAuth) && "1".equals(isOperatorAuth)) {
            search.setBizType(bizType);
        }

        /*TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        search.setEnterpriseId(user.getEnterpriseId());
        search.setOperatorId(user.getOperatorId());
        search.setDataAuth(dataAuth);
        String isPlatformAuth = dataAuth.substring(0, 1);
        String isOperatorAuth = dataAuth.substring(1, 2);
        if ("1".equals(isPlatformAuth) && "1".equals(isOperatorAuth)) {
            search.setBizType(bizType);
        }*/
        StationAllDataVo data = null;
        StatisticsStationNum statisticsStationNum = elecStationService.getStatisticsStationNum(search);
        if (statisticsStationNum!=null){
            data = new  StationAllDataVo();
            data.setStationCount(statisticsStationNum.getStationCount());
            data.setAlternatCount(statisticsStationNum.getManNum());
            data.setDirectCount(statisticsStationNum.getKuaiNum());
            data.setGunCount(statisticsStationNum.getGunCount());
            data.setPileCount(statisticsStationNum.getPileCount());

//            data.setPileMalfunction(statisticsStationNum.getGzNum());
//            data.setSnatching(statisticsStationNum.getCqNum());
//            data.setIdle(statisticsStationNum.getKxNum());
//            data.setOffline(statisticsStationNum.getLxNum());
//            data.setCharging(statisticsStationNum.getCdzNum());
        }
        //StationAllDataVo data = consoleService.countStation(search);
        return TResponse.SUCCESS_DATA(data);
    }

    /**
     * 电桩状态
     */
    @ResponseBody
    @RequestMapping("/countGun")
    public TResponse countGun(String bizType,String dataAuth) {
        StatisticsSearch search = new StatisticsSearch();
        TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        search.setOperatorId(user.getOperatorId());
        search.setEnterpriseId(user.getEnterpriseId());

        search.setDataAuth(dataAuth);
        String isPlatformAuth = dataAuth.substring(0, 1);
        String isOperatorAuth = dataAuth.substring(1, 2);
        if ("1".equals(isPlatformAuth) && "1".equals(isOperatorAuth)) {
            search.setBizType(bizType);
        }
        ElecPileStatusCountVo elecPileStatusCountVo = consoleService.countGun(search);
        return TResponse.SUCCESS_DATA(elecPileStatusCountVo);
    }

    /**
     * 站点订单排名
     */
    @ResponseBody
    @RequestMapping("/countStationOrderRank")
    public TResponse countStationOrderRank(String dateType,String dataAuth) {
        StatisticsSearch search = new StatisticsSearch();
        TenantUser user = ShiroUtils.getSessionUser();
        search.setTenantCode(user.getTenantCode());
        search.setEnterpriseId(user.getEnterpriseId());
        search.setDateType(dateType);
        search.setOperatorId(user.getOperatorId());
        search.setDataAuth(dataAuth);

        List data = consoleService.countStationOrderRank(search);
        return TResponse.SUCCESS_DATA(data);
    }


}
